package com.cloudinnov.logic.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cloudinnov.dao.AttachDao;
import com.cloudinnov.dao.EquipmentInspectionConfigDao;
import com.cloudinnov.dao.EquipmentInspectionResultDao;
import com.cloudinnov.dao.EquipmentInspectionWorkItemDao;
import com.cloudinnov.dao.EquipmentInspectionWorkItemOptionDao;
import com.cloudinnov.logic.EquipmentInspectionConfigLogic;
import com.cloudinnov.model.Attach;
import com.cloudinnov.model.EquipmentInspectionConfig;
import com.cloudinnov.model.EquipmentInspectionResult;
import com.cloudinnov.model.EquipmentInspectionWorkItem;
import com.cloudinnov.model.EquipmentInspectionWorkItemOption;
import com.cloudinnov.model.ProductionLineEquipments;
import com.cloudinnov.utils.CodeUtil;
import com.cloudinnov.utils.CommonUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

@Service("equipmentInspectionConfigLogic")
public class EquipmentInspectionConfigLogicImpl extends BaseLogicImpl<EquipmentInspectionConfig>
		implements EquipmentInspectionConfigLogic {

	private int digit = 5;
	@Autowired
	private EquipmentInspectionConfigDao configDao;
	@Autowired
	private EquipmentInspectionWorkItemDao wiDao;
	@Autowired
	private EquipmentInspectionWorkItemOptionDao equipmentInspectionWorkItemOptionDao;
	@Autowired
	private EquipmentInspectionResultDao equipmentInspectionResultDao;
	@Autowired
	private AttachDao attachDao;

	public int save(EquipmentInspectionConfig equipmentInspectionConfig) {
		String configCode = CodeUtil.inspectionConfigCode(digit);
		equipmentInspectionConfig.setCode(configCode);
		int result = configDao.insert(equipmentInspectionConfig);
		if (result == CommonUtils.SUCCESS_NUM) {
			// 处理工作项
			List<EquipmentInspectionWorkItem> list = new ArrayList<>();
			if (equipmentInspectionConfig.getItems() == null || equipmentInspectionConfig.getItems().length() == 0) {
				return 0;
			}
			List<String> items = JSON.parseArray(equipmentInspectionConfig.getItems(), String.class);

			for (int i = 0; i < items.size(); i++) {
				String itemCode = CodeUtil.inspectionWorkItemsCode(digit);
				EquipmentInspectionWorkItem ewi = new EquipmentInspectionWorkItem();
				ewi.setCustomerCode(equipmentInspectionConfig.getCustomerCode());
				ewi.setEquipmentCode(equipmentInspectionConfig.getEquipmentCode());
				ewi.setLanguage(equipmentInspectionConfig.getLanguage());
				ewi.setCode(itemCode);
				ewi.setConfigCode(configCode);
				JSONObject jsonObj = JSON.parseObject(items.get(i));
				ewi.setName(jsonObj.getString("name"));
				ewi.setDescription(jsonObj.getString("description"));
				ewi.setSelectType(Integer.valueOf(jsonObj.getString("selectType")));
				List<String> itemList = JSON.parseArray(jsonObj.getJSONArray("selectItems").toJSONString(),
						String.class);
				EquipmentInspectionWorkItemOption itemOption = null;
				for (int j = 0; j < itemList.size(); j++) {
					JSONObject selectItem = JSON.parseObject(itemList.get(j));
					itemOption = new EquipmentInspectionWorkItemOption();
					itemOption.setWorkItemCode(itemCode);
					itemOption.setSelectItem(selectItem.getString("name") !=null ? selectItem.getString("name"): "");
					itemOption.setOrderId(j+1);
					equipmentInspectionWorkItemOptionDao.insert(itemOption);
				}
				list.add(ewi);
			}
			// 插入工作项
			int itemsResult = wiDao.insertByList(list);
			// 关联工作项
			if (itemsResult == list.size()) {
				return 1;
			} else {
				return 0;
			}
		} else {
			return 0;
		}
	}

	public Page<EquipmentInspectionConfig> selectListPage(int index, int size, EquipmentInspectionConfig entity,
			boolean isOrderBy) {
		PageHelper.startPage(index, size);
		if (isOrderBy) {
			PageHelper.orderBy("create_time desc");
		}
		List<EquipmentInspectionConfig> list = configDao.selectListByCondition(entity);
		// handle work item
		for (int i = 0, length = list.size(); i < length; i++) {
			List<EquipmentInspectionWorkItem> workItem = wiDao.selectByConfigCode(list.get(i));
			list.get(i).setWorkItems(workItem);
		}

		return (Page<EquipmentInspectionConfig>) list;
	}

	@Override
	public List<EquipmentInspectionConfig> quartzList() {
		String condition = String.valueOf(System.currentTimeMillis());
		return configDao.quartzList(condition);
	}

	public EquipmentInspectionConfig select(EquipmentInspectionConfig entity) {
		EquipmentInspectionConfig result = configDao.selectEntityByCondition(entity);
		List<EquipmentInspectionWorkItem> workItems = wiDao.selectByConfigCode(result);
		for (EquipmentInspectionWorkItem workItem : workItems) {
			EquipmentInspectionWorkItemOption optionModel = null;
			if (workItem.getSelectType() != null) {
				optionModel = new EquipmentInspectionWorkItemOption();
				optionModel.setWorkItemCode(workItem.getCode());
				List<EquipmentInspectionWorkItemOption> options = equipmentInspectionWorkItemOptionDao.selectListByCondition(optionModel);
				List<EquipmentInspectionWorkItem.SelectName> list = new ArrayList<>();
				EquipmentInspectionWorkItem.SelectName item;
				for (int i = 0; i < options.size(); i++) {
					item = new EquipmentInspectionWorkItem().getSelectName();
					item.setName(options.get(i).getSelectItem());
					item.setId(options.get(i).getId());
					list.add(item);
				}
				workItem.setSelectItems(list);
			}
		}
		result.setWorkItems(workItems);
		return result;
	}
	
	public EquipmentInspectionConfig moblieSelect(EquipmentInspectionConfig entity) {
		EquipmentInspectionConfig result = configDao.selectEntityByCondition(entity);
		List<EquipmentInspectionWorkItem> workItems = wiDao.selectByConfigCode(result);
		int currentIndex = 0;
		Attach attach = null;
		for (int k =0; k< workItems.size();k++) {
			if(workItems.get(k) != null && workItems.get(k).getResult()!= null){
				if(k != workItems.size()-1){
					currentIndex ++;
				}
				attach = new Attach();
				attach.setType(AttachLogicImpl.ATTACH_INSPECTION_TYPE);
				attach.setFileType(CommonUtils.UPLOAD_TYPE_MSG_IMAGE_STR);
				attach.setObjectCode(workItems.get(k).getResultCode());
				List<Attach> attachs = attachDao.selectListByCondition(attach);
				String[] urls = new String[attachs.size()];
				for(int i = 0 ; i< attachs.size(); i++){
					urls[i] = attachs.get(i).getUrl();
				}
				workItems.get(k).setFiles(urls);
			}
			EquipmentInspectionWorkItemOption optionModel = null;
			if (workItems.get(k).getSelectType() != null) {
				optionModel = new EquipmentInspectionWorkItemOption();
				optionModel.setWorkItemCode(workItems.get(k).getCode());
				List<EquipmentInspectionWorkItemOption> options = equipmentInspectionWorkItemOptionDao.selectListByCondition(optionModel);
				List<EquipmentInspectionWorkItem.SelectContent> list = new ArrayList<>();
				EquipmentInspectionWorkItem.SelectContent content;
				
				EquipmentInspectionResult equipmentInspectionResult = new EquipmentInspectionResult();
				equipmentInspectionResult.setWorkItemCode(workItems.get(k).getCode());
				EquipmentInspectionResult resultModel = equipmentInspectionResultDao.selectEntityByCondition(equipmentInspectionResult);
				String[] optionIds = null;
				if(resultModel !=null && workItems.get(k).getSelectType() == 1){
					optionIds = resultModel.getResult().split(CommonUtils.SPLIT_COMMA);
				}else if(resultModel !=null && workItems.get(k).getSelectType() == 2){
					optionIds = new String[] {resultModel.getResult()};
				}
				for (int i = 0; i < options.size(); i++) {
					content = new EquipmentInspectionWorkItem().getSelectContent();
					content.setContent(options.get(i).getSelectItem());
					content.setId(options.get(i).getId());
					if(optionIds!=null && optionIds.length>0){
						for (int j = 0; j < optionIds.length; j++) {	
							if(options.get(i).getId() == Integer.parseInt(optionIds[j])){
								content.setChecked(true);
							}
						}
					}else{
						content.setChecked(false);
					}
					list.add(content);
				}
				workItems.get(k).setSelectContents(list);
			}
		}
		result.setWorkItems(workItems);
		result.setCurrentIndex(currentIndex);
		return result;
	}

	public int update(EquipmentInspectionConfig entity) {
		int returnCode = configDao.updateByCondition(entity);
		// workItem info
		if (returnCode == CommonUtils.SUCCESS_NUM) {
			List<EquipmentInspectionWorkItem> list = null;
			if (entity.getItems() == null || entity.getItems().length() == 0) {
				return 0;
			}
			JSONArray workItemsJson = JSON.parseArray(entity.getItems());
			String[] deleteCodes = new String[workItemsJson.size()];
			for(int i = 0;i <workItemsJson.size(); i++){
				EquipmentInspectionWorkItem model = JSON.parseObject(workItemsJson.getString(i), EquipmentInspectionWorkItem.class);
				if(model.getCode() !=null){
					deleteCodes[i] = model.getCode();
					if(model !=null && model.getCode() !=null){
						EquipmentInspectionWorkItemOption itemOption = null;
						for (int j = 0; j < model.getSelectItems().size(); j++) {
							itemOption = new EquipmentInspectionWorkItemOption();
							itemOption.setWorkItemCode(model.getCode());
							itemOption.setSelectItem(model.getSelectItems().get(j).getName() !=null ? model.getSelectItems().get(j).getName() : "");
							itemOption.setOrderId(j+1);
							if(model.getSelectItems().get(j).getId()==null){
								equipmentInspectionWorkItemOptionDao.insert(itemOption);
							}else{
								itemOption.setId(model.getSelectItems().get(j).getId());
								equipmentInspectionWorkItemOptionDao.updateByCondition(itemOption);
							}
						}
					}
					returnCode = wiDao.updateByCondition(model);
				}else{
					list = new ArrayList<>();
					String itemCode = CodeUtil.inspectionWorkItemsCode(digit);
					EquipmentInspectionWorkItem ewi = new EquipmentInspectionWorkItem();
					ewi.setCustomerCode(entity.getCustomerCode());
					ewi.setEquipmentCode(entity.getEquipmentCode());
					ewi.setLanguage(entity.getLanguage());
					ewi.setCode(itemCode);
					ewi.setConfigCode(entity.getCode());
					ewi.setName(model.getName());
					ewi.setDescription(model.getDescription() !=null ? model.getDescription() : "");
					ewi.setSelectType(model.getSelectType());
					EquipmentInspectionWorkItemOption itemOption = null;
					for (int j = 0; j < model.getSelectItems().size(); j++) {
						itemOption = new EquipmentInspectionWorkItemOption();
						itemOption.setWorkItemCode(itemCode);
						itemOption.setOrderId(j+1);
						itemOption.setSelectItem(model.getSelectItems().get(j).getName() !=null ? model.getSelectItems().get(j).getName() : "");
						equipmentInspectionWorkItemOptionDao.insert(itemOption);
					}
					list.add(ewi);
					// 插入工作项
					returnCode = wiDao.insertByList(list);
				}
			}
			EquipmentInspectionWorkItem model = new EquipmentInspectionWorkItem();
			model.setCodes(deleteCodes);
			wiDao.deleteByCondition(model);
		} else {
			return 0;
		}
		if(returnCode >= CommonUtils.SUCCESS_NUM){
			return CommonUtils.SUCCESS_NUM;
		}
		return CommonUtils.DEFAULT_NUM;
	}

	@Override
	public Page<EquipmentInspectionConfig> search(int index, int size, String country, String province, String city,
			String key, String oemCode, String integratorCode, String type, String language,
			ProductionLineEquipments ple) {
		PageHelper.startPage(index, size);
		Map<String, Object> map = new HashMap<String, Object>();

		if (ple.getCustomerCode() != null && !ple.getCustomerCode().equals("")) {
			map.put("customerCode", ple.getCustomerCode());
			map.put("customerCodes", ple.getCustomerCode().split(","));
		}
		if (ple.getProductionLineCode() != null && !ple.getProductionLineCode().equals("")) {
			map.put("productionLineCode", ple.getCustomerCode());
			map.put("productionLineCodes", ple.getCustomerCode().split(","));
		}
		map.put("integratorCode", integratorCode);
		map.put("oemCode", oemCode);
		map.put("country", country);
		map.put("province", province);
		map.put("city", city);
		map.put("name", key);
		map.put("type", type);
		map.put("language", language);
		return (Page<EquipmentInspectionConfig>) configDao.search(map);
	}

	@Override
	public Map<String, Object> getConfigStateByEquipmentCode(EquipmentInspectionConfig entity) {
		Map<String, Object> map = new HashMap<>();
		PageHelper.orderBy("eic.create_time desc");
		EquipmentInspectionConfig result = null;
		List<EquipmentInspectionConfig> list = configDao.selectListByCondition(entity);
		if(list !=null && list.size()>0){
			result = list.get(0);
		}
		if(result != null){
			map.put("configCode", result.getCode());
			List<EquipmentInspectionWorkItem> workItems = wiDao.selectByConfigCode(result);
			Iterator<EquipmentInspectionWorkItem> it = workItems.iterator();
			EquipmentInspectionResult equipmentInspectionResult = null;
		    while(it.hasNext()){
		    	EquipmentInspectionWorkItem workItem = (EquipmentInspectionWorkItem) it.next();
		    	equipmentInspectionResult = new EquipmentInspectionResult();
				equipmentInspectionResult.setWorkItemCode(workItem.getCode());
				EquipmentInspectionResult resultModel = equipmentInspectionResultDao.selectEntityByCondition(equipmentInspectionResult);//查询工作项下的结果
		      	if(resultModel!=null && resultModel.getWorkItemCode().equals(workItem.getCode())) {
		      		it.remove();
		        }
		    }
		    if(workItems.size()==CommonUtils.DEFAULT_NUM){
		    	map.put("state", 2);//设备下巡检结果已填写完毕
		    }else if(workItems.size()>=CommonUtils.DEFAULT_NUM){
		    	map.put("state", 3);//设备下巡检结果未填写完毕
		    }
		}else{
			map.put("state", 1);//设备下无巡检配置
		}
		return map;
	}

	@Override
	public List<EquipmentInspectionConfig> getConfigListByEquipmentCode(EquipmentInspectionConfig entity) {
		PageHelper.orderBy("eic.create_time desc");
		List<EquipmentInspectionConfig> list = configDao.selectListByCondition(entity);
		if(list != null){
			for(EquipmentInspectionConfig config : list){
				List<EquipmentInspectionWorkItem> workItems = wiDao.selectByConfigCode(config);
				Iterator<EquipmentInspectionWorkItem> it = workItems.iterator();
				EquipmentInspectionResult equipmentInspectionResult = null;
			    while(it.hasNext()){
			    	EquipmentInspectionWorkItem workItem = (EquipmentInspectionWorkItem) it.next();
			    	equipmentInspectionResult = new EquipmentInspectionResult();
					equipmentInspectionResult.setWorkItemCode(workItem.getCode());
					EquipmentInspectionResult resultModel = equipmentInspectionResultDao.selectEntityByCondition(equipmentInspectionResult);//查询工作项下的结果
			      	if(resultModel!=null && resultModel.getWorkItemCode().equals(workItem.getCode())) {
			      		it.remove();
			        }
			    }
			    if(workItems.size() == CommonUtils.DEFAULT_NUM){
			    	config.setState(2);//设备下巡检结果已填写完毕
			    }else if(workItems.size() >= CommonUtils.DEFAULT_NUM){
			    	config.setState(3);//设备下巡检结果未填写完毕
			    }
			}
			
		}
		return list;
	}

}
